import { Link, useLocation } from "@tanstack/react-router";
import { LoaderCircle } from "lucide-react";
import type { ReactElement } from "react";
import reactIconUrl from "@/assets/react.svg";
import Avatar from "@/components/Avatar";
import Button from "@/components/Button";
import useAuthStore from "@/store/auth";

type Props = {
  children?: ReactElement | undefined;
};

export default function RootLayout(p: Props) {
  const loc = useLocation();
  const auth = useAuthStore((state) => state);

  return (
    <div
      className="min-h-screen grid grid-rows-[auto_1fr_auto]"
      style={{ background: "linear-gradient(45deg, #EEEDF5, #f9f8ff)" }}
    >
      <nav className="px-6 py-2 flex items-center gap-4 bg-purple-50/95 border-b border-gray-300 sticky top-0 z-10 h-12">
        <img className="w-6" src="/vite.svg" alt="vite icon" />
        <img className="w-6" src={reactIconUrl} alt="react icon" />
        <Link to="/">Home</Link>
        <Link to="/demo">Demo</Link>
        {auth.status === "failed" && <Link to="/login">Login</Link>}
        {auth.status === "loading" && <LoaderCircle className="animate-spin" />}
        {auth.status === "ok" && (
          <>
            <div className="inline-flex items-center gap-4">
              <Avatar src={auth.avatar} alt="my avatar" /> {auth.username}
            </div>
            <Button size="sm" variant="outline" onClick={() => auth.logout()}>
              Logout
            </Button>
          </>
        )}
      </nav>
      <main>{p.children}</main>
      <footer className="bg-purple-50 border-t border-gray-300 px-4 py-2">
        <p>Footer</p>
        <p>
          <strong>Current route path:</strong> {loc.pathname}
        </p>
      </footer>
    </div>
  );
}
